package com.example.k12.base

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.WindowManager
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.ToastUtils
import com.example.k12.R
import java.lang.reflect.ParameterizedType


abstract class BaseDialog<T : ViewBinding>(
    context: Context
) :
    Dialog(context, R.style.myDialog2) {
    lateinit var mBinding: T
    var mHeight: Int = 0//高
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("merchantassistant", "当前进入的Dialog: " + javaClass.name)
        try {
            window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN or WindowManager.LayoutParams.FLAG_FULLSCREEN)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        //获取泛型
        val superclass = javaClass.genericSuperclass
        val aClass = (superclass as ParameterizedType).actualTypeArguments[0] as Class<*>
        try {
            val method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
            mBinding = method.invoke(null, layoutInflater) as T
        } catch (e: Exception) {
            e.printStackTrace()
        }
        setContentView(mBinding.root)
        initParam()
        initData()
    }

    /**
     * 设置 高度
     */
    fun setMHeight(mHeight: Int): BaseDialog<T> {
        this.mHeight = mHeight
        return this
    }


    protected abstract fun getWidth(): Int

    private fun initParam() {
        window?.apply {
            // 添加蒙版支持标志
            addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)

            val attrs = attributes.apply {
                dimAmount = 0.6f  // 昏暗度 (0.0完全透明 - 1.0完全不透明)
                gravity = Gravity.CENTER
                height = if (mHeight == 0) WindowManager.LayoutParams.WRAP_CONTENT else mHeight
                width = if (getWidth() == 0) WindowManager.LayoutParams.WRAP_CONTENT else getWidth()
            }
            attributes = attrs
        }
    }


    protected abstract fun initData()

    fun showToast(msg: String?) {
        ToastUtils.showLong(msg)
    }

    fun showToast(resId: Int) {
        ToastUtils.showShort(resId)
    }

    /**
     * 判断是否是快速点击
     */
    private var mLastClickTime: Long = 0

    /**
     * 增强型防抖点击（首次点击立即响应，后续100ms内屏蔽）
     * @param block 点击事件处理逻辑
     */
    open fun safeClick(block: () -> Unit) {
        val currentTime = System.currentTimeMillis()
        if (currentTime - mLastClickTime > 300) {
            mLastClickTime = currentTime
            block()
        }
    }
}